package com.tjian.fafa.user.base.mainBody;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tjian.fafa.user.R;
import com.tjian.fafa.user.base.ConnectedApp;
import com.tjian.fafa.user.base.bean.TabMsgItemEntity;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.chatServices.ChatService;
import com.tjian.fafa.user.base.chatter.ChatActivity;
import com.tjian.fafa.user.config.ConfigOfFafa;
import com.tjian.fafa.user.util.image.ImageUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainTabMyPage extends Activity
{

    private static MainTabMyPage mainTabMyPage;

    private View viewOfPage;
    private Context context;

    private List<Integer> mListOfIds;
    private List<TabMsgItemEntity> mListOfEntity;

    private int mNotifId = 1;
    private LinearLayout layoutLogin;
    private LinearLayout dataRelativeLayout;

    private LinearLayout extend_function_relativelayout;
    private LinearLayout phone_login_linearlayout;

    private RelativeLayout login_areaRelativeLayout;
    private LinearLayout settingsRelativeLayout;
    private TextView login_nameTextView;
    private TextView curLocationTextView;
    private ImageView avatarImage;

    public static MainTabMyPage getInstance()
    {
        if (mainTabMyPage == null)
        {
            mainTabMyPage = new MainTabMyPage();
        }
        return mainTabMyPage;
    }

    private MainTabMyPage()
    {
    }

    public void onInit(View view, Context context)
    {
        viewOfPage = view;
        this.context = context;
    }

    public List<TabMsgItemEntity> getListOfEntity()
    {
        return mListOfEntity;
    }

    public void onCreate()
    {
        mainTabMyPage = this;
        layoutLogin = (LinearLayout) viewOfPage.findViewById(R.id.main_tab_my_login);
        dataRelativeLayout = (LinearLayout) viewOfPage.findViewById(R.id.main_tab_my_data);
        settingsRelativeLayout = (LinearLayout) viewOfPage.findViewById(R.id.main_tab_my_setting);
        extend_function_relativelayout = (LinearLayout) viewOfPage.findViewById(R.id.extend_function_relativelayout_id);
        phone_login_linearlayout = (LinearLayout) viewOfPage.findViewById(R.id.phone_login_linearlayout_id);
        login_areaRelativeLayout = (RelativeLayout) viewOfPage.findViewById(R.id.login_area);
        login_nameTextView = (TextView) viewOfPage.findViewById(R.id.login_name);
        curLocationTextView = (TextView) viewOfPage.findViewById(R.id.tabmsg_item_text_latest_msg);

        avatarImage = (ImageView) viewOfPage.findViewById(R.id.avatar_id);

        UserInfo userInfo = ConnectedApp.getInstance().getUserInfo();
        //验证是否登录。
        if (userInfo == null)
        {
            layoutLogin.setVisibility(View.VISIBLE);
        }
        else
        {
            login_areaRelativeLayout.setVisibility(View.VISIBLE);
            String loginName = userInfo.getName();
            String curLocation = userInfo.getCurLocation();
            login_nameTextView.setText(loginName);
            curLocationTextView.setText(curLocation);
            String urlString = ConfigOfFafa.projectWebsiteUrl + userInfo.getmAvatarImagePath();
            Bitmap map = ImageUtil.getBitMapForStringURL(urlString);
            avatarImage.setImageBitmap(map);
        }

        layoutLogin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainBodyActivity.getInstance().gotoMyLoginPageActivity();
            }
        });
        dataRelativeLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainBodyActivity.getInstance().gotoMainMyDataPage();
            }
        });
        settingsRelativeLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainBodyActivity.getInstance().gotoSettingsActivity();
            }
        });

        extend_function_relativelayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                MainBodyActivity.getInstance().gotoExtendFunction();
            }
        });

        phone_login_linearlayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setClass(context, com.tjian.fafa.user.module.login.PhoneLoginActivity_fafa.class);
                context.startActivity(intent);
            }
        });
    }

    /**
     * 通过URL返回网络的BitMap图片
     *
     * @param urlString
     * @return Bitmap
     */
    public static Bitmap getBitMapForStringURLOld(String urlString)
    {

        URL url = null;
        Bitmap bitmap = null;

        try
        {
            url = new URL(urlString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true);
            conn.connect();

            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            is.close();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return bitmap;
    }

    public void onUpdateByUserinfo(UserInfo user, String sentence, String time,
                                   boolean updateNotif, String imagePath)
    {
        if (mListOfIds.contains(user.getId()))
        {
            int idx = mListOfIds.indexOf(user.getId());
            mListOfIds.remove(idx);
            mListOfEntity.remove(idx);
        }
        mListOfIds.add(0, user.getId());
        mListOfEntity.add(0, new TabMsgItemEntity(user.getId(), user.getAvatarId(), user.getName(), sentence, time, imagePath));


        if (updateNotif)
        {
            onUpdateNotification(user.getId(), sentence);
        }
    }

    public void onUpdateById(int id, int avatarId, String name, String sentence, String time,
                             boolean updateNotif, String imagePath)
    {
        if (mListOfIds.contains(id))
        {
            int idx = mListOfIds.indexOf(id);
            mListOfIds.remove(idx);
            mListOfEntity.remove(idx);
        }
        mListOfIds.add(0, id);
        mListOfEntity.add(0, new TabMsgItemEntity(id, avatarId, name, sentence, time, imagePath));

        if (updateNotif)
        {
            onUpdateNotification(id, sentence);
        }
    }

    @SuppressWarnings("deprecation")
    public void onUpdateNotification(int id, String sentence)
    {
        int icon = R.drawable.new_launcher;
        CharSequence tickerText = sentence;
        long when = System.currentTimeMillis();
        Notification mNotification = new Notification(icon, tickerText, when);

        mNotification.flags = Notification.FLAG_NO_CLEAR;
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        if (!isForeGround())
        {
            mNotification.defaults |= Notification.DEFAULT_SOUND;
            mNotification.defaults |= Notification.DEFAULT_VIBRATE;
        }
        mNotification.contentView = null;

        Intent intent;
        if (id < 0)
        {
            intent = new Intent(context,
                    FrdRequestNotifActivity.class);
        }
        else
        {
            intent = new Intent(context,
                    ChatActivity.class);
            ChatService.getInstance().setEnterFromNotification(true);
            ChatService.getInstance().setEnterFromNotificationId(id);
        }

        PendingIntent contentIntent = PendingIntent.getActivity(
                context, 0, intent, 0);

        mNotification = new Notification.Builder(context)
                .setContentTitle("new message")
                .setContentText(sentence)
                .setContentIntent(contentIntent).build();

        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(this.mNotifId, mNotification);
    }

    public boolean isForeGround()
    {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
        String curPackageName = foregroundTaskInfo.baseActivity.getPackageName();

        String myPackageName = context.getPackageName();

        if (curPackageName.equals(myPackageName))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


}
